﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Navigation;
using Fayshine.VA.Helpers;
using Fayshine.VA.Models;
using Fayshine.VA.RIAService.Web;
using Fayshine.VA.ViewModels;
using Visifire.Charts;
using LocalBusyIndicator = Fayshine.VA.Controls.BusyIndicator;

namespace Fayshine.VA.Views.Reports
{
    public partial class DailyReports : Page
    {

        private bool m_IsFinshed1 = false;
        private bool m_IsFinshed2 = false;
        private StatisticsReportViewModel m_ViewModel;

        public DailyReports()
        {
            InitializeComponent();
            this.Loaded += new RoutedEventHandler(DailyReports_Loaded);
        }

        #region Event Methods

        private void DailyReports_Loaded(object sender, RoutedEventArgs e)
        {
            LocalBusyIndicator indicator = Application.Current.RootVisual as LocalBusyIndicator;
            indicator.IsBusy = true;
            datePicker.SelectedDate = DateTime.Now;
            m_ViewModel = new StatisticsReportViewModel();
            m_ViewModel.ResetHisotryChartEvent += new ResetHistoryChartEventHandler(m_ViewModel_ResetHisotryChartEvent);
            //m_ViewModel.AppendHistoryPassengerFlow += new AppendHistoryPassengerFlowEventHandler(m_ViewModel_AppendHistoryPassengerFlow);
            m_ViewModel.AppendMultiHistoryPassenger += new AppendMultiHistoryPassengerEventHandler(m_ViewModel_AppendMultiHistoryPassenger);
            this.DataContext = m_ViewModel;

            m_ViewModel.GetAllAreas();
        }

        private void m_ViewModel_AppendMultiHistoryPassenger(string title, bool isIn, params List<HistoryPassengerFlow>[] historyPassengerFlows)
        {
            this.Dispatcher.BeginInvoke(delegate()
            {
                var firstHistoryPassengerFlow = historyPassengerFlows[0];
                var secondHistoryPassengerFlow = historyPassengerFlows[1];

                SetDayGateInOurCompareChart(firstHistoryPassengerFlow);
                SetDayGateProcentChart(firstHistoryPassengerFlow);
                SetPassengerSexChart();
                SetPassengerAgeChart();
                SetDayInChart(secondHistoryPassengerFlow);
                SetDayOutChart(secondHistoryPassengerFlow);
                SetStrandarChart(secondHistoryPassengerFlow);
                SetYearDayChart(historyPassengerFlows[2]);
                SetDayPassengerBusyAndSaleChart(historyPassengerFlows[3]);
                m_IsFinshed1 = true;

                LocalBusyIndicator indicator = Application.Current.RootVisual as LocalBusyIndicator;
                indicator.IsBusy = false;

            });
        }

        private void m_ViewModel_ResetHisotryChartEvent()
        {
            this.Dispatcher.BeginInvoke(delegate()
            {

                if (vcGateCompare != null)
                {
                    vcGateCompare.AxesX.Clear();
                    vcGateCompare.TrendLines.Clear();
                    vcGateCompare.Series.Clear();
                    vcGateCompare.Titles.Clear();
                }

                if (vcGatePrecentCompare != null)
                {
                    vcGatePrecentCompare.AxesX.Clear();
                    vcGatePrecentCompare.TrendLines.Clear();
                    vcGatePrecentCompare.Series.Clear();
                    vcGatePrecentCompare.Titles.Clear();
                }

                if (vcGatePrecentCompare2 != null)
                {
                    vcGatePrecentCompare2.AxesX.Clear();
                    vcGatePrecentCompare2.TrendLines.Clear();
                    vcGatePrecentCompare2.Series.Clear();
                    vcGatePrecentCompare2.Titles.Clear();
                }

                if (vcDayInChart != null)
                {
                    vcDayInChart.AxesX.Clear();
                    vcDayInChart.TrendLines.Clear();
                    vcDayInChart.Series.Clear();
                    vcDayInChart.Titles.Clear();
                }
                if (vcDayOutChart != null)
                {
                    vcDayOutChart.AxesX.Clear();
                    vcDayOutChart.TrendLines.Clear();
                    vcDayOutChart.Series.Clear();
                    vcDayOutChart.Titles.Clear();
                }
                if (vcStrandChart != null)
                {
                    vcStrandChart.AxesX.Clear();
                    vcStrandChart.TrendLines.Clear();
                    vcStrandChart.Series.Clear();
                    vcStrandChart.Titles.Clear();
                }

                if (vcChartAge != null)
                {
                    vcChartAge.AxesX.Clear();
                    vcChartAge.TrendLines.Clear();
                    vcChartAge.Series.Clear();
                    vcChartAge.Titles.Clear();
                }

                if (vcChartSex != null)
                {
                    vcChartSex.AxesX.Clear();
                    vcChartSex.TrendLines.Clear();
                    vcChartSex.Series.Clear();
                    vcChartSex.Titles.Clear();
                }
                if (vcYearDayChart != null)
                {
                    vcYearDayChart.AxesX.Clear();
                    vcYearDayChart.TrendLines.Clear();
                    vcYearDayChart.Series.Clear();
                    vcYearDayChart.Titles.Clear();
                }

                if (vcDaySaleChart != null)
                {
                    vcDaySaleChart.AxesX.Clear();
                    vcDaySaleChart.TrendLines.Clear();
                    vcDaySaleChart.Series.Clear();
                    vcDaySaleChart.Titles.Clear();
                }

                if (vcDayBuyChart != null)
                {
                    vcDayBuyChart.AxesX.Clear();
                    vcDayBuyChart.TrendLines.Clear();
                    vcDayBuyChart.Series.Clear();
                    vcDayBuyChart.Titles.Clear();
                }

            });
        }

        private void cmbAreas_DropDownClosed(object sender, EventArgs e)
        {
            if (m_ViewModel != null)
            {
                List<area> selectedArea = new List<area>();
                var selectAreaExt = m_ViewModel.AreaExtends.Where(a => a.IsSelected).ToList();
                selectAreaExt.ForEach(b =>
                {
                    area temp = b.Tag as area;
                    selectedArea.Add(temp);
                });

                if (selectedArea.Count > 0)
                {
                    cbItemDisplay.Content = selectedArea.Count > 1 ? selectedArea[0].Name + "..." : selectedArea[0].Name;

                }
                else
                {
                    cbItemDisplay.Content = string.Empty;
                }
                cmbAreas.SelectedItem = null;
                cmbAreas.SelectedItem = cbItemDisplay;

                m_ViewModel.SelectAreasChanged(selectedArea);
            }
        }

        // Executes when the user navigates to this page.
        protected override void OnNavigatedTo(NavigationEventArgs e)
        {
        }

        private void btnSearch_Click(object sender, RoutedEventArgs e)
        {
            string msg = string.Empty;
            
            m_ViewModel.UpdateCheckedAreas();

            if (!FayshineManager.Instance.ValidateAreaGateInputs(m_ViewModel.CheckedAreas,
                m_ViewModel.CheckedGates, ref msg))
            {
                MessageBox.Show(msg);
            }
            else
            {
                DateTime dateTime = datePicker.SelectedDate.Value;
                lblTitleTop.Text = GetChartSubTitle() + " 客流日报表";
                lblTitleTop2.Text = dateTime.ToShortDateString();

                LocalBusyIndicator indicator = Application.Current.RootVisual as LocalBusyIndicator;
                indicator.IsBusy = true;
                m_IsFinshed1 = false;
                m_IsFinshed2 = false;
                m_ViewModel.RefreshDayReport(true, dateTime);
            }
        }

        #endregion

        #region Private Methods

        private void ResetBusyIndicator()
        {
            if (m_IsFinshed2 && m_IsFinshed1)
            {
                LocalBusyIndicator indicator = Application.Current.RootVisual as LocalBusyIndicator;
                indicator.IsBusy = false;
            }
        }

        private void SetDayGateInOurCompareChart(List<HistoryPassengerFlow> dayGatePassengerFlows)
        {
            List<HistoryPassengerFlow> sources = dayGatePassengerFlows.OrderBy(o => o.DisplayTitle).ToList();

            DateTime time = datePicker.SelectedDate.Value;

            string title1 = GetChartSubTitle();

            Title vcChart1Title = new Visifire.Charts.Title();
            vcChart1Title.Text = time.ToShortDateString() + title1 + " 各通道进出客流对比";
            vcGateCompare.Titles.Add(vcChart1Title);

            DataSeries series = ChartHelper.GetDataSeries(RenderAs.Column, "进", ChartValueTypes.Auto);
            series.DataMappings.Add(ChartHelper.GetDataMapping("AxisXLabel", "DisplayTitle"));
            series.DataMappings.Add(ChartHelper.GetDataMapping("YValue", "InCount"));
            series.DataSource = sources;
            vcGateCompare.Series.Add(series);

            DataSeries series2 = ChartHelper.GetDataSeries(RenderAs.Column, "出", ChartValueTypes.Auto);
            series2.DataMappings.Add(ChartHelper.GetDataMapping("AxisXLabel", "DisplayTitle"));
            series2.DataMappings.Add(ChartHelper.GetDataMapping("YValue", "OutCount"));
            series2.DataSource = sources;
            vcGateCompare.Series.Add(series2);

        }

        private void SetDayGateProcentChart(List<HistoryPassengerFlow> dayGatePassengerFlows)
        {
            List<HistoryPassengerFlow> sources = dayGatePassengerFlows.OrderBy(o => o.DisplayTitle).ToList();
            DateTime time = datePicker.SelectedDate.Value;
            string title1 = GetChartSubTitle();

            Title vcChart1Title = new Visifire.Charts.Title();
            vcChart1Title.Text = time.ToShortDateString() + title1 + " 进客流百分比";
            vcGatePrecentCompare.Titles.Add(vcChart1Title);

            DataSeries series = ChartHelper.GetDataSeries(RenderAs.Pie, "进", ChartValueTypes.Auto);
            series.DataMappings.Add(ChartHelper.GetDataMapping("AxisXLabel", "DisplayTitle"));
            series.DataMappings.Add(ChartHelper.GetDataMapping("YValue", "InCount"));
            series.LabelText = "#AxisXLabel (#Percentage%)";
            series.DataSource = sources;
            vcGatePrecentCompare.Series.Add(series);

            Title vcChart1Title2 = new Visifire.Charts.Title();
            vcChart1Title2.Text = time.ToShortDateString() + title1 + " 出客流百分比";
            vcGatePrecentCompare2.Titles.Add(vcChart1Title2);

            DataSeries series2 = ChartHelper.GetDataSeries(RenderAs.Pie, "出", ChartValueTypes.Auto);
            series2.DataMappings.Add(ChartHelper.GetDataMapping("AxisXLabel", "DisplayTitle"));
            series2.DataMappings.Add(ChartHelper.GetDataMapping("YValue", "OutCount"));
            series2.LabelText = "#AxisXLabel (#Percentage%)";
            series2.DataSource = sources;
            vcGatePrecentCompare2.Series.Add(series2);

        }

        private void SetPassengerSexChart()
        {
            DateTime dateTime = datePicker.SelectedDate.Value;
            DateTime startTime = new DateTime(dateTime.Year, dateTime.Month, dateTime.Day, 0, 0, 0);
            DateTime endTime = startTime.AddDays(1);

            List<HistoryPassengerFlow> sexHistoryPassengerFlows = m_ViewModel.GetPassengerflowsBySex(startTime, endTime);

            string title1 = GetChartSubTitle();

            Title vcChart1Title = new Visifire.Charts.Title();
            vcChart1Title.Text = dateTime.ToShortDateString() + title1 + " 男女客流占比图";
            vcChartSex.Titles.Add(vcChart1Title);

            DataSeries series = ChartHelper.GetDataSeries(RenderAs.Pie, "客流", ChartValueTypes.Auto);
            series.DataMappings.Add(ChartHelper.GetDataMapping("AxisXLabel", "SexName"));
            series.DataMappings.Add(ChartHelper.GetDataMapping("YValue", "AllInOut"));
            series.LabelText = "#AxisXLabel (#Percentage%)";
            series.DataSource = sexHistoryPassengerFlows;
            vcChartSex.Series.Add(series);


        }

        private void SetPassengerAgeChart()
        {
            DateTime dateTime = datePicker.SelectedDate.Value;
            DateTime startTime = new DateTime(dateTime.Year, dateTime.Month, dateTime.Day, 0, 0, 0);
            DateTime endTime = startTime.AddDays(1);

            List<HistoryPassengerFlow> ageHistoryPassengerFlows = m_ViewModel.GetAgeDurationPassengerFlow(startTime, endTime);

            Axis xAxis = new Axis();
            xAxis.AxisMinimum = 0;
            xAxis.AxisMaximum = 120;

            xAxis.IntervalType = IntervalTypes.Number;
            xAxis.Interval = 5;

            vcChartAge.AxesX.Add(xAxis);

            string title1 = GetChartSubTitle();

            Title vcChart1Title = new Visifire.Charts.Title();
            vcChart1Title.Text = dateTime.ToShortDateString() + title1 + " 各年龄段客流图";
            vcChartAge.Titles.Add(vcChart1Title);


            DataSeries series = ChartHelper.GetDataSeries(RenderAs.Line, "进", ChartValueTypes.Numeric);
            series.DataMappings.Add(ChartHelper.GetDataMapping("XValue", "Age"));
            series.DataMappings.Add(ChartHelper.GetDataMapping("YValue", "AllInOut"));
            series.DataSource = ageHistoryPassengerFlows;
            vcChartAge.Series.Add(series);
        }

        private void SetYearDayChart(List<HistoryPassengerFlow> firstHistoryPassengerFlow)
        {
            DateTime dateTime = datePicker.SelectedDate.Value;
            int year = dateTime.Year;

            Axis xAxis = new Axis();
            DateTime minDateTime = new DateTime(year, 1, 1, 0, 0, 0);
            DateTime maxDateTime = minDateTime.AddYears(1);
            xAxis.ValueFormatString = "MM 月";
            xAxis.IntervalType = IntervalTypes.Months;
            xAxis.Interval = 1;
            vcYearDayChart.AxesX.Add(xAxis);

            Title vcChart1Title = new Visifire.Charts.Title();
            vcChart1Title.Text = year + "年" + GetChartSubTitle() + " 每日客流分布图";
            vcYearDayChart.Titles.Add(vcChart1Title);

            var selectAreas = m_ViewModel.AreaExtends.Where(a => a.IsSelected).ToList();

            if (selectAreas.Count > 1)
            {
                selectAreas.each(s => {

                    DataSeries tempSeries = ChartHelper.GetDataSeries(RenderAs.Line, s.Name, ChartValueTypes.Date);
                    tempSeries.DataMappings.Add(ChartHelper.GetDataMapping("XValue", "HistoryTime"));
                    tempSeries.DataMappings.Add(ChartHelper.GetDataMapping("YValue", "AllInOut"));
                    tempSeries.DataSource = m_ViewModel.GetYearPassengerflowsByArea(s.ID, year);
                    vcYearDayChart.Series.Add(tempSeries);
                });
            }

            DataSeries series = ChartHelper.GetDataSeries(RenderAs.Line, "所选店铺（和）", ChartValueTypes.Date);
            series.DataMappings.Add(ChartHelper.GetDataMapping("XValue", "HistoryTime"));
            series.DataMappings.Add(ChartHelper.GetDataMapping("YValue", "AllInOut"));
            series.DataSource = firstHistoryPassengerFlow;
            vcYearDayChart.Series.Add(series);

        }

        private void SetDayInChart(List<HistoryPassengerFlow> historyPassengerFlows)
        {
            Axis xAxis = new Axis();
            DateTime minDateTime = historyPassengerFlows.Select(s => s.HistoryTime).Min();
            DateTime maxDateTime = historyPassengerFlows.Select(s => s.HistoryTime).Max();
            xAxis.AxisMinimum = minDateTime;
            xAxis.AxisMaximum = maxDateTime;

            xAxis.ValueFormatString = "HH:mm";
            xAxis.IntervalType = IntervalTypes.Hours;
            xAxis.Interval = 1;

            vcDayInChart.AxesX.Add(xAxis);

            int max = 0;
            double avg = 0;
            max = historyPassengerFlows.Select(s => s.InCount).Max();
            avg = historyPassengerFlows.Select(s => s.InCount).Average();

            DateTime time = datePicker.SelectedDate.Value;
            string title1 = GetChartSubTitle();

            Title vcChart1Title = new Visifire.Charts.Title();
            vcChart1Title.Text = time.ToShortDateString() + title1 + " 进客流分布图";
            vcDayInChart.Titles.Add(vcChart1Title);

            TrendLine maxLine = new TrendLine();
            maxLine.Value = max;
            maxLine.LabelText = "最大:" + max.ToString();
            maxLine.FlowDirection = System.Windows.FlowDirection.LeftToRight;
            maxLine.HorizontalAlignment = System.Windows.HorizontalAlignment.Right;

            TrendLine avgLine = new TrendLine();
            avgLine.Value = avg;
            avgLine.LabelText = "平均:" + Convert.ToInt32(avg).ToString();
            avgLine.FlowDirection = System.Windows.FlowDirection.LeftToRight;
            vcDayInChart.TrendLines.Add(maxLine);
            vcDayInChart.TrendLines.Add(avgLine);

            var selectAreas = m_ViewModel.AreaExtends.Where(a => a.IsSelected).ToList();

            if (selectAreas.Count > 1)
            {
                selectAreas.each(s =>
                {

                    DataSeries tempSeries = ChartHelper.GetDataSeries(RenderAs.Line, s.Name, ChartValueTypes.Time);
                    tempSeries.DataMappings.Add(ChartHelper.GetDataMapping("XValue", "HistoryTime"));
                    tempSeries.DataMappings.Add(ChartHelper.GetDataMapping("YValue", "InCount"));
                    tempSeries.DataSource = m_ViewModel.GetDayDurationPassengerByArea(s.ID, time);
                    vcDayInChart.Series.Add(tempSeries);
                });
            }

            DataSeries series = ChartHelper.GetDataSeries(RenderAs.Line, "所选店铺（和）", ChartValueTypes.Time);
            series.DataMappings.Add(ChartHelper.GetDataMapping("XValue", "HistoryTime"));
            series.DataMappings.Add(ChartHelper.GetDataMapping("YValue", "InCount"));
            series.DataSource = historyPassengerFlows;
            vcDayInChart.Series.Add(series);
        }

        private void SetDayOutChart(List<HistoryPassengerFlow> historyPassengerFlows)
        {
            Axis xAxis = new Axis();
            DateTime minDateTime = historyPassengerFlows.Select(s => s.HistoryTime).Min();
            DateTime maxDateTime = historyPassengerFlows.Select(s => s.HistoryTime).Max();
            xAxis.AxisMinimum = minDateTime;
            xAxis.AxisMaximum = maxDateTime;
            xAxis.ValueFormatString = "HH:mm";
            xAxis.IntervalType = IntervalTypes.Hours;
            xAxis.Interval = 1;

            vcDayOutChart.AxesX.Add(xAxis);

            int max = 0;
            double avg = 0;
            max = historyPassengerFlows.Select(s => s.OutCount).Max();
            avg = historyPassengerFlows.Select(s => s.OutCount).Average();

            DateTime time = datePicker.SelectedDate.Value;
            string title1 = GetChartSubTitle();

            Title vcChart1Title = new Visifire.Charts.Title();
            vcChart1Title.Text = time.ToShortDateString() + title1 + " 出客流分布图";
            vcDayOutChart.Titles.Add(vcChart1Title);

            TrendLine maxLine = new TrendLine();
            maxLine.Value = max;
            maxLine.LabelText = "最大:" + max.ToString();
            maxLine.FlowDirection = System.Windows.FlowDirection.LeftToRight;
            maxLine.HorizontalAlignment = System.Windows.HorizontalAlignment.Right;

            TrendLine avgLine = new TrendLine();
            avgLine.Value = avg;
            avgLine.LabelText = "平均:" + Convert.ToInt32(avg).ToString();
            avgLine.FlowDirection = System.Windows.FlowDirection.LeftToRight;
            vcDayOutChart.TrendLines.Add(maxLine);
            vcDayOutChart.TrendLines.Add(avgLine);

            var selectAreas = m_ViewModel.AreaExtends.Where(a => a.IsSelected).ToList();

            if (selectAreas.Count > 1)
            {
                selectAreas.each(s =>
                {

                    DataSeries tempSeries = ChartHelper.GetDataSeries(RenderAs.Line, s.Name, ChartValueTypes.Time);
                    tempSeries.DataMappings.Add(ChartHelper.GetDataMapping("XValue", "HistoryTime"));
                    tempSeries.DataMappings.Add(ChartHelper.GetDataMapping("YValue", "OutCount"));
                    tempSeries.DataSource = m_ViewModel.GetDayDurationPassengerByArea(s.ID, time);
                    vcDayOutChart.Series.Add(tempSeries);
                });
            }

            DataSeries series = ChartHelper.GetDataSeries(RenderAs.Line, "所选店铺（和）", ChartValueTypes.Time);
            series.DataMappings.Add(ChartHelper.GetDataMapping("XValue", "HistoryTime"));
            series.DataMappings.Add(ChartHelper.GetDataMapping("YValue", "OutCount"));
            series.DataSource = historyPassengerFlows;
            vcDayOutChart.Series.Add(series);
        }

        private void SetStrandarChart(List<HistoryPassengerFlow> historyPassengerFlow)
        {
            Axis xAxis = new Axis();
            DateTime minDateTime = historyPassengerFlow.Select(s => s.HistoryTime).Min();
            DateTime maxDateTime = historyPassengerFlow.Select(s => s.HistoryTime).Max();
            xAxis.AxisMinimum = minDateTime;
            xAxis.AxisMaximum = maxDateTime;

            xAxis.ValueFormatString = "HH:mm";
            xAxis.IntervalType = IntervalTypes.Hours;
            xAxis.Interval = 1;

            vcStrandChart.AxesX.Add(xAxis);

            DateTime time = datePicker.SelectedDate.Value;
            string title1 = GetChartSubTitle();

            Title vcChart1Title = new Visifire.Charts.Title();
            vcChart1Title.Text = time.ToShortDateString() + title1 + " 滞留人数分布图";
            vcStrandChart.Titles.Add(vcChart1Title);

            //DataSeries accInSeries = ChartHelper.GetDataSeries(RenderAs.Area, "累计进", ChartValueTypes.Time);
            //accInSeries.DataMappings.Add(ChartHelper.GetDataMapping("XValue", "HistoryTime"));
            //accInSeries.DataMappings.Add(ChartHelper.GetDataMapping("YValue", "AccumulateInCount"));
            //accInSeries.DataSource = historyPassengerFlow;

            //DataSeries accOutSeries = ChartHelper.GetDataSeries(RenderAs.Area, "累计出", ChartValueTypes.Time);
            //accOutSeries.DataMappings.Add(ChartHelper.GetDataMapping("XValue", "HistoryTime"));
            //accOutSeries.DataMappings.Add(ChartHelper.GetDataMapping("YValue", "AccumulateOutCount"));
            //accOutSeries.DataSource = historyPassengerFlow;

            var selectAreas = m_ViewModel.AreaExtends.Where(a => a.IsSelected).ToList();

            if (selectAreas.Count > 1)
            {
                selectAreas.each(s =>
                {

                    DataSeries tempSeries = ChartHelper.GetDataSeries(RenderAs.Line, s.Name, ChartValueTypes.Time);
                    tempSeries.DataMappings.Add(ChartHelper.GetDataMapping("XValue", "HistoryTime"));
                    tempSeries.DataMappings.Add(ChartHelper.GetDataMapping("YValue", "StrandedCount"));
                    tempSeries.DataSource = m_ViewModel.GetDayDurationPassengerByArea(s.ID, time);
                    vcStrandChart.Series.Add(tempSeries);
                });
            }

            DataSeries strandedSeries = ChartHelper.GetDataSeries(RenderAs.Area, "所选店铺（和）", ChartValueTypes.Time);
            strandedSeries.DataMappings.Add(ChartHelper.GetDataMapping("XValue", "HistoryTime"));
            strandedSeries.DataMappings.Add(ChartHelper.GetDataMapping("YValue", "StrandedCount"));
            strandedSeries.DataSource = historyPassengerFlow;
            //vcStrandChart.Series.Add(accInSeries);
            //vcStrandChart.Series.Add(accOutSeries);
            vcStrandChart.Series.Add(strandedSeries);
        }

        private void SetDayPassengerBusyAndSaleChart(List<HistoryPassengerFlow> firstHistoryPassengerFlow)
        {
            string title = datePicker.SelectedDate.Value.ToShortDateString();

            m_ViewModel.AreaExtends.each(a =>
            {

                if (a.IsSelected)
                {
                    title = title + "-" + a.Name + "-";
                }

            });

            SetChartStatistics(title + " 客流与提袋率对比", firstHistoryPassengerFlow, vcDayBuyChart, true);
            SetChartStatistics(title + " 客流与销售额对比", firstHistoryPassengerFlow, vcDaySaleChart, false);
        }

        private void SetChartStatistics(string title, List<HistoryPassengerFlow> firstHistoryPassengerFlow, Chart chart, bool isPercent)
        {
            Axis xAxis = new Axis();
            DateTime minDateTime = firstHistoryPassengerFlow.Select(s => s.HistoryTime).Min();
            DateTime maxDateTime = firstHistoryPassengerFlow.Select(s => s.HistoryTime).Max();
            xAxis.AxisMinimum = minDateTime;
            xAxis.AxisMaximum = maxDateTime;
            xAxis.ValueFormatString = "HH:mm";
            xAxis.IntervalType = IntervalTypes.Hours;
            xAxis.Interval = 1;
            chart.AxesX.Add(xAxis);

            Title vcChart1Title = new Visifire.Charts.Title();
            vcChart1Title.Text = title;
            chart.Titles.Add(vcChart1Title);

            DataSeries series = ChartHelper.GetDataSeries(RenderAs.Column, "进人数", ChartValueTypes.Time);
            series.AxisYType = AxisTypes.Primary;
            series.DataMappings.Add(ChartHelper.GetDataMapping("XValue", "HistoryTime"));
            series.DataMappings.Add(ChartHelper.GetDataMapping("YValue", "InCount"));
            series.DataSource = firstHistoryPassengerFlow;
            chart.Series.Add(series);

            DataSeries series2 = ChartHelper.GetDataSeries(RenderAs.Column, "成交数", ChartValueTypes.Time);
            series2.AxisYType = AxisTypes.Primary;
            series2.DataMappings.Add(ChartHelper.GetDataMapping("XValue", "HistoryTime"));
            series2.DataMappings.Add(ChartHelper.GetDataMapping("YValue", "TradeCount"));
            series2.DataSource = firstHistoryPassengerFlow;
            chart.Series.Add(series2);

            if (isPercent)
            {
                Axis syAxis = new Axis();
                syAxis.AxisType = AxisTypes.Secondary;
                syAxis.AxisMinimum = 0;
                syAxis.AxisMaximum = 1;
                syAxis.ValueFormatString = "#0.##%";
                syAxis.IntervalType = IntervalTypes.Number;
                syAxis.Interval = 0.1;
                chart.AxesY.Add(syAxis);

                DataSeries series3 = ChartHelper.GetDataSeries(RenderAs.Line, "提袋率", ChartValueTypes.Time);
                series3.AxisYType = AxisTypes.Secondary;
                series3.DataMappings.Add(ChartHelper.GetDataMapping("XValue", "HistoryTime"));
                series3.DataMappings.Add(ChartHelper.GetDataMapping("YValue", "SalePercent"));
                series3.DataSource = firstHistoryPassengerFlow;
                chart.Series.Add(series3);
            }
            else
            {
                Axis syAxis = new Axis();
                syAxis.AxisType = AxisTypes.Secondary;
                chart.AxesY.Add(syAxis);

                DataSeries series3 = ChartHelper.GetDataSeries(RenderAs.Line, "销售额", ChartValueTypes.Time);
                series3.AxisYType = AxisTypes.Secondary;
                series3.DataMappings.Add(ChartHelper.GetDataMapping("XValue", "HistoryTime"));
                series3.DataMappings.Add(ChartHelper.GetDataMapping("YValue", "TradeMoney"));
                series3.DataSource = firstHistoryPassengerFlow;
                chart.Series.Add(series3);
            }
        }

        private DataSeries GetWorkDayDataSeries(DateTime startTime, DateTime endTime, DayOfWeek dayOfWeek)
        {
            List<DayOfWeek> dayOfWeeks = new List<DayOfWeek>();
            dayOfWeeks.Add(dayOfWeek);
            var workDaySource = m_ViewModel.GetHistoryPassengerByWeek(false, startTime, endTime, dayOfWeeks);

            string title = GetDateForWeek(startTime, endTime, dayOfWeek).ToShortDateString() + " " + GetWeekDayString(dayOfWeek);

            DataSeries series = ChartHelper.GetDataSeries(RenderAs.Line, title, ChartValueTypes.Time);
            series.DataMappings.Add(ChartHelper.GetDataMapping("XValue", "HistoryTime"));
            series.DataMappings.Add(ChartHelper.GetDataMapping("YValue", "AllInOut"));
            series.DataSource = workDaySource;

            return series;
        }

        private string GetWeekDayString(DayOfWeek dayOfWeek)
        {
            string weekDay = "星期一";
            switch (dayOfWeek)
            {
                case DayOfWeek.Sunday:
                    weekDay = "星期日";
                    break;
                case DayOfWeek.Monday:
                    weekDay = "星期一";
                    break;
                case DayOfWeek.Tuesday:
                    weekDay = "星期二";
                    break;
                case DayOfWeek.Wednesday:
                    weekDay = "星期三";
                    break;
                case DayOfWeek.Thursday:
                    weekDay = "星期四";
                    break;
                case DayOfWeek.Friday:
                    weekDay = "星期五";
                    break;
                case DayOfWeek.Saturday:
                    weekDay = "星期六";
                    break;
            }

            return weekDay;
        }

        private string GetChartSubTitle()
        {
            string title1 = string.Empty;

            var selectAreaExts = m_ViewModel.AreaExtends.Where(a => a.IsSelected).ToList();
            if (selectAreaExts.Count == 1)
            {
                title1 = selectAreaExts[0].Name;
            }
            else if (selectAreaExts.Count > 1)
            {
                title1 = "各店铺";
            }

            return title1;
        }

        private DateTime GetDateForWeek(DateTime start, DateTime end, DayOfWeek dayOfWeek)
        {
            DateTime a = start;

            while (start <= end)
            {
                if (start.DayOfWeek == dayOfWeek)
                {
                    a = start;
                    break;
                }
                start = start.AddDays(1);
            }

            return a;
        }

        #endregion

        private void btnExport_Click(object sender, RoutedEventArgs e)
        {
            SaveFileDialog fsd = new SaveFileDialog();
            fsd.Filter = "PDF (*.pdf)|*.pdf|*PNG (*.png)|*.png";

            if (fsd.ShowDialog() == true)
            {
                LocalBusyIndicator indicator = Application.Current.RootVisual as LocalBusyIndicator;
                indicator.IsBusy = true;
                this.Dispatcher.BeginInvoke(delegate()
                {
                    FayshineManager.Instance.ExportToDisk(fsd, spContent);
                });
            }
        }

    }
}
